<template>
  <div class="content_main" v-loading="loading" element-loading-text="加载中...">
    <!-- <el-header class="appcontainer">
      <el-row class="header_tabs" :style="{ width: lookW + 'px' }" justify="space-evenly">
        <el-col :span="4" v-for="(item, index) in listItem" class="item_title" :class="{ is_bg: index == itemIndex }"
          :key="index" @click="onclickIndex(index)">{{ item }}</el-col>
      </el-row>
    </el-header> -->
    <div class="header">
      <h3>{{ route.name === 'commodity1' ? '新增成品' : '新增配件' }}</h3>
      <div class="btn_group">
        <HPlainButton @click.stop="saveData(formInfo)">保存</HPlainButton>
        <HButton @click.stop="onCancel">取消</HButton>
      </div>
    </div>

    <div class="body">
      <div class="basic_info_container">
        <el-collapse
          id="sy0"
          :model-value="activeNames.includes('1') ? '1' : ''"
          class="bor_padding"
          @change="handleChange('1')"
        >
          <div style="width: 100%" ref="dom"></div>
          <el-collapse-item name="1">
            <template #title>
              <div class="icon_title">
                <el-icon v-if="activeNames.includes('1')">
                  <CaretBottom />
                </el-icon>
                <el-icon v-else>
                  <CaretRight />
                </el-icon>
                <span>基本信息</span>
              </div>
            </template>
            <div class="main_content">
              <el-form
                ref="formInfo"
                :model="infoForm"
                :rules="rulesForm"
                label-width="90px"
                class="demo-ruleForm"
              >
                <div class="justify">
                  <div>
                    <!--商品编号-->
                    <div style="display: flex; align-items: center; gap: 4px">
                      <el-form-item label="商品编号" prop="code" class="code">
                        <el-input
                          clearable
                          placeholder="如无编号系统自动生成"
                          v-model="infoForm.code"
                        />
                      </el-form-item>
                      <el-tooltip content="用于商家内部管理所使用的自定义简易编号" placement="top">
                        <el-icon style="margin-bottom: 15px" color="#999" size="18">
                          <WarningFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                    <!--商品类型-->
                    <el-form-item label="商品类型" prop="type">
                      <el-select
                        v-model="infoForm.type"
                        placeholder="请选择成品/配件"
                        @change="typeChange"
                        :disabled="route.params.id != undefined"
                      >
                        <el-option
                          v-for="item in options2"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                    <!--商品品牌-->
                    <el-form-item label="商品品牌">
                      <el-select
                        v-model="infoForm.brand"
                        placeholder="请选择商品品牌"
                        filterable
                        clearable
                        reserve-keyword
                        remote-show-suffix
                        :loading="brandLoading"
                        :filter-method="searchBrandSelect"
                      >
                        <el-option
                          v-for="item in brandOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                  <div>
                    <!--商品名称-->
                    <el-form-item label="商品名称" prop="name">
                      <el-input v-model="infoForm.name" placeholder="请输入商品名称" clearable />
                    </el-form-item>
                    <!--商品型号-->
                    <el-form-item label="商品型号" prop="model">
                      <el-input v-model="infoForm.model" placeholder="请输入商品型号" clearable />
                    </el-form-item>
                    <!--商品分类-->
                    <el-form-item label="商品分类">
                      <el-select
                        v-model="infoForm.class"
                        placeholder="请选择商品分类"
                        filterable
                        clearable
                        reserve-keyword
                        remote-show-suffix
                        :loading="typeLoading"
                        :filter-method="searchTypeSelect"
                      >
                        <el-option
                          v-for="item in typeOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                  <div>
                    <!--商品单位-->
                    <el-form-item label="商品单位" prop="unit">
                      <el-select
                        v-model="infoForm.unit"
                        placeholder="请选择商品单位"
                        filterable
                        clearable
                        reserve-keyword
                        remote-show-suffix
                        :loading="unitLoading"
                        :filter-method="searchUnitSelect"
                      >
                        <el-option
                          v-for="item in unitOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                    <!--质保登记-->
                    <el-form-item label="质保登记" v-if="infoForm.type == '成品'">
                      <el-select clearable v-model="infoForm.war" placeholder="启用/关闭">
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                    <!--关联商家-->
                    <el-form-item label="关联商家">
                      <el-select
                        placeholder="请选择关联商家"
                        filterable
                        clearable
                        v-model="infoForm.factoryIds"
                        :filter-method="getFactoryOptional"
                        :loading="getFactorySelectPageLoading"
                        reserve-keyword
                        remote-show-suffix
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        :max-collapse-tags="1"
                      >
                        <el-option
                          v-for="item in factoryOptional"
                          :key="item.id"
                          :value="item.id"
                          :label="item.name"
                        />
                      </el-select>
                    </el-form-item>
                    <!--供应商-->
                    <el-form-item label="供应商" prop="supplier" v-if="infoForm.type == '配件'">
                      <el-input v-model="infoForm.supplier" placeholder="配件供应商" clearable />
                    </el-form-item>
                  </div>
                  <!--联系电话-->
                  <el-form-item label="联系电话" prop="phone" v-if="infoForm.type == '配件'">
                    <el-input v-model="infoForm.phone" placeholder="供应商联系电话" clearable />
                  </el-form-item>
                </div>
                <el-form-item label="商品图片" class="phone_add">
                  <el-upload
                    action="#"
                    multiple
                    list-type="picture-card"
                    accept=".jpg,.png,.webp,.gif"
                    :auto-upload="false"
                    v-model:file-list="infoForm.fileList"
                    @change="getProImages"
                  >
                    <template #file="{ file }">
                      <div>
                        <el-image
                          class="el-upload-list__item-thumbnail"
                          :src="file.url"
                          alt=""
                          fit="scale-down"
                        />
                        <span class="el-upload-list__item-actions">
                          <span
                            class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview(file)"
                          >
                            <el-icon>
                              <zoom-in />
                            </el-icon>
                          </span>
                          <span
                            v-if="!disabled"
                            class="el-upload-list__item-delete"
                            @click="handleRemove(file)"
                          >
                            <el-icon>
                              <Delete />
                            </el-icon>
                          </span>
                        </span>
                      </div>
                    </template>
                    <div class="plus_add">
                      <el-icon size="16">
                        <Plus />
                      </el-icon>
                      上传
                    </div>
                  </el-upload>
                  <el-dialog v-model="dialogVisible" draggable top="8vh">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" class="img_view" />
                  </el-dialog>
                </el-form-item>
                <!--商品货号-->
                <!-- <el-form-item label="商品货号" prop="item">
                    <el-input
                      v-model="infoForm.item"
                      placeholder="如无货号系统自动生成"
                      clearable
                    />
                  </el-form-item> -->
                <!--商品图片-->
              </el-form>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <!--商品规格-->
      <el-collapse
        id="sy1"
        :model-value="activeNames.includes('2') ? '2' : ''"
        class="bor_padding"
        @change="handleChange('2')"
      >
        <el-collapse-item name="2">
          <template #title>
            <div style="display: flex; gap: 5px; align-items: center">
              <div>
                <el-icon v-if="activeNames.includes('2')">
                  <CaretBottom />
                </el-icon>
                <el-icon v-else>
                  <CaretRight />
                </el-icon>
                <span>商品规格</span>
              </div>
              <HPlainButton @click.stop="addLineData" :height="22" :padding-lr="6">
                添加商品规格
              </HPlainButton>
            </div>
          </template>
          <div class="main_content">
            <!--<el-form>-->
            <!--<el-form-item>-->
            <!--<template #label>-->
            <!--</template>-->
            <!--</el-form-item>-->
            <!-- <el-form-item :label="item.title + ' :'" v-for="(item, index) in specData" :key="index">
              <el-checkbox-group
                v-model="listData[index].checkList"
                @change="changeModel(listData[index])"
              >
                <el-checkbox :label="i" v-for="(i, key) in item.checkList" :key="key"
                  ><span class="label_color">{{ i }}</span></el-checkbox
                >
              </el-checkbox-group>
            </el-form-item> -->
            <!--</el-form>-->
            <div class="table_list">
              <el-table
                stripe
                resizable
                :border="true"
                :data="tableData"
                style="width: 100%"
                max-height="330"
              >
                <el-table-column label="序号" width="50" fixed>
                  <template v-slot="item">
                    <span class="index"> {{ item.$index + 1 }} </span>
                    <div class="delete flex-center">
                      <el-icon
                        color="rgba(245, 108, 108, 1)"
                        size="16"
                        class="dele-icon"
                        @click.stop="deleteLineData(item.$index, item.row)"
                      >
                        <RemoveFilled />
                      </el-icon>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="规格名称" width="140">
                  <template v-slot="item">
                    <el-input clearable v-model="item.row.name" />
                  </template>
                </el-table-column>
                <el-table-column label="启用" width="50">
                  <template v-slot="item">
                    <el-checkbox v-model="item.row.enabled" size="large" />
                  </template>
                </el-table-column>
                <el-table-column label="主图" width="80">
                  <template v-slot="item">
                    <el-upload
                      class="img-uploader"
                      accept=".jpg,.png,.webp,.gif"
                      :auto-upload="false"
                      :show-file-list="false"
                      :on-change="handleChangeImg"
                    >
                      <el-image
                        v-if="item.row.image"
                        :src="item.row.image"
                        fit="contain"
                        style="width: 32px; height: 32px"
                        @click="getImgIndex(item.$index)"
                      />
                      <el-icon
                        class="avatar-uploader-icon"
                        size="18"
                        v-else
                        @click="getImgIndex(item.$index)"
                      >
                        <Plus />
                      </el-icon>
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column width="80">
                  <template #header>
                    价格
                    <el-popover placement="top-start" :width="160" trigger="hover">
                      <h5 style="margin-bottom: 10px">批量填充价格</h5>
                      <el-input
                        placeholder="请输入"
                        v-model="num"
                        clearable
                        @keyup.enter="changeNumber(1)"
                      ></el-input>
                      <div style="display: flex; justify-content: end; margin-top: 10px">
                        <el-button
                          type="primary"
                          color="#007cff"
                          style="padding: 0 4px; height: 20px"
                          @click="changeNumber(1)"
                          >确定</el-button
                        >
                      </div>
                      <template #reference>
                        <span class="multiple_btn">批量</span>
                      </template>
                    </el-popover>
                  </template>
                  <template v-slot="item">
                    <el-input
                      clearable
                      v-model="item.row.price"
                      @input="item.row.price = item.row.price.replace(/\D/g, '')"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="过保价格" width="80" v-if="infoForm.type == '配件'">
                  <template v-slot="item">
                    <el-input
                      clearable
                      v-model="item.row.overPrice"
                      @input="item.row.overPrice = item.row.overPrice.replace(/\D/g, '')"
                    />
                  </template>
                </el-table-column>
                <el-table-column width="120">
                  <template #header>
                    质保周期
                    <el-popover placement="top-start" :width="160" trigger="hover">
                      <h5 style="margin-bottom: 10px">批量填充质保周期</h5>
                      <el-input
                        placeholder="请输入"
                        v-model="num2"
                        clearable
                        @keyup.enter="changeNumber(2)"
                      />
                      <div style="display: flex; justify-content: end; margin-top: 10px">
                        <el-button
                          type="primary"
                          color="#007cff"
                          style="padding: 0 4px; height: 20px"
                          @click="changeNumber(2)"
                          >确定</el-button
                        >
                      </div>
                      <template #reference>
                        <span class="multiple_btn">批量</span>
                      </template>
                    </el-popover>
                  </template>
                  <template v-slot="item">
                    <div class="warr_day">
                      <el-input
                        clearable
                        v-model="item.row.warrantyDay"
                        style="width: 60px"
                        @input="item.row.warrantyDay = item.row.warrantyDay.replace(/\D/g, '')"
                      />
                      <span class="day">天</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="sku码" width="140">
                  <template v-slot="item">
                    <el-input clearable v-model="item.row.code" placeholder="如无则系统自动生成" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-collapse
        id="sy2"
        :model-value="activeNames.includes('3') ? '3' : ''"
        class="bor_padding"
        @change="handleChange('3')"
      >
        <el-collapse-item name="3">
          <template #title>
            <div>
              <el-icon v-if="activeNames.includes('3')">
                <CaretBottom />
              </el-icon>
              <el-icon v-else>
                <CaretRight />
              </el-icon>
              <span>商品参数</span>
            </div>
          </template>
          <div class="main_content">
            <el-container>
              <el-aside class="pop_aside" width="55%">
                <el-form
                  ref="formSpec"
                  label-position="right"
                  :model="paraForm"
                  class="demo-ruleForm"
                  :rules="rulesForm"
                >
                  <!-- <div> -->
                  <el-form-item label="选择参数" prop="para">
                    <el-select
                      clearable
                      v-model="paraForm.para"
                      placeholder="请选择参数"
                      @change="getFields"
                    >
                      <el-option
                        v-for="item in paraForm.paraOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                  <!-- </div> -->
                  <div class="oard_form oard_form_">
                    <div
                      v-for="(item, itindex) in paraForm.fieldInfo"
                      :key="itindex"
                      class="form-row"
                    >
                      <el-form-item
                        :label="item.name"
                        :required="item.required"
                        :prop="`fieldInfo[${itindex}][${
                          item.type === 5 || item.type === 6 || item.type === 7 ? 'imgarr' : 'val'
                        }]`"
                        :rules="[
                          {
                            required: item.required,
                            message: item.tip,
                            trigger: ['blur', 'change'],
                          },
                        ]"
                      >
                        <!-- 文本 -->
                        <el-input
                          v-if="item.type === 1"
                          :placeholder="item.tip"
                          type="text"
                          v-model="item.val"
                          clearable
                        ></el-input>
                        <!-- 多行文本 -->
                        <el-input
                          v-if="item.type === 2"
                          class="form-control"
                          :rows="1"
                          v-model="item.val"
                          type="textarea"
                          :placeholder="item.tip"
                          show-word-limit
                        ></el-input>
                        <!-- 单选 -->
                        <el-select
                          v-model="item.val"
                          v-if="item.type === 3 && item.strs.length > 3"
                          :placeholder="item.tip"
                          clearable
                        >
                          <el-option
                            v-for="(str, strindex) in item.strs"
                            :key="strindex"
                            :label="str"
                            :value="str"
                          />
                        </el-select>
                        <el-radio-group v-else-if="item.type === 3" v-model="item.val">
                          <el-radio v-for="(str, index) in item.strs" :key="index" :value="str">{{
                            str
                          }}</el-radio>
                        </el-radio-group>
                        <!-- 多选 -->
                        <el-select
                          v-model="item.val"
                          v-if="item.type === 4 && item.strs.length > 3"
                          :placeholder="item.tip"
                          clearable
                          multiple
                          collapse-tags
                          collapse-tags-tooltip
                        >
                          <el-option
                            v-for="(str, strindex) in item.strs"
                            :key="strindex"
                            :label="str"
                            :value="str"
                          />
                        </el-select>
                        <el-checkbox-group v-else-if="item.type === 4" v-model="item.val">
                          <el-checkbox
                            v-for="(str, strindex) in item.strs"
                            :key="strindex"
                            :value="str"
                            >{{ str }}</el-checkbox
                          >
                        </el-checkbox-group>

                        <!-- 图片 -->
                        <div
                          class="upload_file"
                          v-if="item.type === 5 || item.type === 6 || item.type === 7"
                        >
                          <el-upload
                            :auto-upload="false"
                            v-model="item.imgarr"
                            :accept="
                              item.type == 5 ? 'image/*' : item.type == 6 ? '.pdf' : 'video/*'
                            "
                            drag
                            action="#"
                            multiple
                            :show-file-list="false"
                            :on-change="
                              (file) => {
                                handleChange1(file, item)
                              }
                            "
                          >
                            <el-icon class="up_icon"><upload-filled /></el-icon>
                            <div>点击上传图片或者文件</div>
                          </el-upload>
                          <ul class="ul_list">
                            <li class="li_item" v-for="(it, index) in item.imgarr" :key="index">
                              <div class="li_item_left">
                                <img
                                  :src="pdf"
                                  alt=""
                                  style="width: 30px; height: 30px; cursor: pointer"
                                  @click.stop="lookFile(it.image, '附件')"
                                  v-if="
                                    (it.name
                                      ? it.name
                                      : it.image.split('/')[it.image.split('/').length - 1]
                                    ).replace(/.+\./, '') == 'pdf'
                                  "
                                />
                                <el-icon
                                  style="cursor: pointer"
                                  v-else-if="
                                    it.file
                                      ? it.file.type.includes('video/')
                                      : /\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4)$/.test(
                                          it.image.toLowerCase(),
                                        )
                                  "
                                  size="30"
                                  @click.stop="lookFile(it.image, '视频')"
                                >
                                  <Film />
                                </el-icon>
                                <el-image
                                  v-else
                                  :preview-src-list="[it.image]"
                                  style="width: 30px; height: 30px"
                                  :src="it.image"
                                  fit="contain"
                                />

                                <el-tooltip effect="dark" placement="top">
                                  <template #content>
                                    {{
                                      it.name
                                        ? it.name
                                        : it.image.split('/')[it.image.split('/').length - 1]
                                    }}
                                  </template>
                                  <span class="pic_name">{{
                                    it.name
                                      ? it.name
                                      : it.image.split('/')[it.image.split('/').length - 1]
                                  }}</span>
                                </el-tooltip>
                              </div>
                              <el-icon
                                size="16"
                                style="cursor: pointer"
                                @click.stop="deleteItem1(item, index)"
                              >
                                <Delete />
                              </el-icon>
                            </li>
                          </ul>
                        </div>
                      </el-form-item>
                    </div>
                  </div>
                </el-form>
              </el-aside>
              <el-main>
                <el-table
                  stripe
                  resizable
                  :border="true"
                  :data="selfData"
                  style="width: 100%"
                  height="270"
                >
                  <el-table-column label="序号" width="50" fixed show-overflow-tooltip>
                    <template v-slot="item">
                      <span> {{ item.$index + 1 }} </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="自定义参数名称">
                    <template v-slot="item">
                      <el-input
                        clearable
                        v-model="item.row.name"
                        placeholder="请输入参数名称"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="参数值">
                    <template v-slot="item">
                      <div class="can_shu">
                        <el-input
                          clearable
                          v-model="item.row.val"
                          placeholder="请输入参数值"
                        ></el-input>
                        <div class="icons">
                          <el-icon color="#007cff" class="icon" size="20" @click="addParameter">
                            <CirclePlusFilled />
                          </el-icon>
                          <el-icon
                            class="icon"
                            color="rgba(245, 108, 108, 1)"
                            size="20"
                            v-if="selfData.length > 1"
                            @click="deleteParameter(item.$index, item.row.id)"
                          >
                            <RemoveFilled />
                          </el-icon>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-main>
            </el-container>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-collapse
        v-if="infoForm.type == '成品'"
        id="sy3"
        :model-value="activeNames.includes('4') ? '4' : ''"
        class="bor_padding"
        @change="handleChange('4')"
      >
        <el-collapse-item name="4">
          <template #title>
            <div>
              <el-icon v-if="activeNames.includes('4')"> <CaretBottom /> </el-icon
              ><el-icon v-else>
                <CaretRight />
              </el-icon>
              <span>商品资料</span>
            </div>
          </template>
          <div class="main_content">
            <div style="display: flex; gap: 5px">
              <HPlainButton @click="productDrawerShow">
                <el-icon size="14" class="icon_btn">
                  <Document />
                </el-icon>
                商品说明书
                <el-icon class="icon_arr_right">
                  <ArrowRight />
                </el-icon>
              </HPlainButton>
              <HPlainButton @click="vidoeDrawerShow">
                <el-icon size="14" class="icon_btn">
                  <VideoCameraFilled />
                </el-icon>
                商品视频
                <el-icon class="icon_arr_right">
                  <ArrowRight />
                </el-icon>
              </HPlainButton>
              <HPlainButton @click="onShowSystemUpgrade">
                <el-icon size="14" class="icon_btn">
                  <Link />
                </el-icon>
                增加自定义链接
                <el-icon class="icon_arr_right">
                  <ArrowRight />
                </el-icon>
              </HPlainButton>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-collapse
        id="sy4"
        :model-value="activeNames.includes('5') ? '5' : ''"
        class="bor_padding"
        @change="handleChange('5')"
      >
        <el-collapse-item name="5">
          <template #title>
            <div>
              <el-icon v-if="activeNames.includes('5')">
                <CaretBottom />
              </el-icon>
              <el-icon v-else>
                <CaretRight />
              </el-icon>
              <span>商品详情</span>
            </div>
          </template>
          <WangEdior :all_data="ediorData" ref="wangEdior" />
        </el-collapse-item>
      </el-collapse>

      <!-- 文件查看 -->
      <el-dialog
        :title="`查看${file.type}`"
        v-model="dialogContract"
        :draggable="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
      >
        <iframe
          :src="`${file.file}`"
          width="100%"
          height="100%"
          style="height: 700px"
          frameborder="0"
        ></iframe>
      </el-dialog>

      <!--修改商品规格弹窗  -->
      <el-dialog
        v-model="dialogspec"
        title="商品规格"
        width="40%"
        append-to-body
        destroy-on-close
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <el-checkbox-group v-model="checkList" class="spec_show">
          <el-checkbox :value="item.value" v-for="(item, index) in selectspecdata" :key="index"
            ><span class="label_color">{{ item.title }}</span></el-checkbox
          >
        </el-checkbox-group>
        <template #footer>
          <div style="display: flex; justify-content: flex-end">
            <HButton @click="Confirm" is-modal type="primary">确定</HButton>
            <HButton @click="dialogspec = false" is-modal> 取消 </HButton>
          </div>
        </template>
      </el-dialog>

      <!-- 说明书弹窗 -->
      <el-drawer
        v-model="productDrawer"
        title="关联说明书"
        size="700px"
        append-to-body
        destroy-on-close
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <div class="pro_information">
          <p>根据当前产品所需要的相关说明书数据进行关联，后期展示和数据查询快速匹配</p>
          <el-transfer
            v-model="filtervalue"
            :titles="['说明书库', '已关联说明书']"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入搜索内容"
            :data="insData"
          >
            <template #default="{ option }">
              <div class="list_item">
                <span>{{ option.label }}</span
                ><el-icon>
                  <Picture />
                </el-icon>
              </div>
            </template>
          </el-transfer>
        </div>

        <template #footer>
          <footer class="btn_drawer" style="display: flex; justify-content: flex-end; gap: 10px">
            <HButton is-modal type="primary" @click="saveInsbooks">保存</HButton>
            <HButton is-modal @click="productDrawer = false">取消</HButton>
          </footer>
        </template>
      </el-drawer>

      <!-- 视频弹窗 -->
      <el-drawer
        v-model="videoDialog"
        title="关联视频"
        append-to-body
        destroy-on-close
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        size="700px"
      >
        <div class="pro_information">
          <p>根据当前产品所需要的相关视频数据进行关联，后期展示和数据查询快速匹配</p>
          <el-transfer
            v-model="videoValue"
            :titles="['视频库', '已关联视频']"
            filterable
            :filter-method="filterVideo"
            filter-placeholder="请输入搜索内容"
            :data="videoData"
          >
            <template #default="{ option }">
              <div class="list_item">
                <span>{{ option.label }}</span
                ><el-icon>
                  <Picture />
                </el-icon>
              </div>
            </template>
          </el-transfer>
        </div>

        <template #footer>
          <footer class="btn_drawer" style="display: flex; justify-content: flex-end; gap: 10px">
            <HButton is-modal type="primary" @click="saveVideo">保存</HButton>
            <HButton is-modal @click="videoDialog = false">取消</HButton>
          </footer>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onBeforeUnmount, onMounted, reactive, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import type { FormInstance, FormRules, UploadProps, UploadFile } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import WangEdior from '@/components/WangEdior/index.vue'
  import { useSettingStore } from '@/store/modules/setting'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import pdf from './../../../assets/image/pdf.png'
  import * as _ from 'lodash'
  import {
    typePageSelect,
    brandPageSelect,
    unitPageSelect,
    paramPageSelect,
    getParamFields,
    productSave,
    getInfo,
    getInsDetail,
    getVideoDetail,
    spareSave,
    getSpareInfo,
  } from '@/api/goodsInfo'
  import { proAnnexUpload, deleteFile } from '@/api/upload'
  import { instrList, videoList } from '@/api/knowledge'
  import { orderAnnexUpload, orderVideoUpload } from '@/api/upload'
  import {
    ArrowRight,
    CaretBottom,
    CaretRight,
    CirclePlusFilled,
    Delete,
    Document,
    Plus,
    RemoveFilled,
    VideoCameraFilled,
    ZoomIn,
    Link,
  } from '@element-plus/icons-vue'
  import useFactorySelectPageService from '@/views/order/new/services/factorySelectPage'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.good.goodForm,
  })

  /**
   * 使用品牌商家下拉选项服务
   */
  const { getFactorySelectPageLoading, getFactorySelectPageFn, factoryOptional } =
    useFactorySelectPageService

  /**
   * 获取品牌商家下拉选项请求参数
   */
  const getFactoryOptionalParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  /**
   * 获取品牌商家下拉选项
   */
  const getFactoryOptional = _.throttle((query: string) => {
    if (getFactoryOptionalParam.value.name !== query) {
      getFactoryOptionalParam.value.name = query
      getFactorySelectPageFn(getFactoryOptionalParam.value)
    }
  }, 500)

  const TagsViewStore = useTagsViewStore()
  const router = useRouter()
  const route = useRoute()
  const nodekey = localStorage.getItem('nodeKey')
  const listItem = ref(['基本信息', '商品规格', '商品参数', '商品资料', '商品详情'])
  const num = ref()
  const num2 = ref()
  // 批量填充数量
  const changeNumber = (val) => {
    switch (val) {
      case 1:
        if (num.value) {
          tableData.value.forEach((item) => {
            item.price = num.value
          })
        }
        break
      case 2:
        if (num2.value) {
          tableData.value.forEach((item) => {
            item.warrantyDay = num2.value
          })
        }
        break
      default:
        break
    }
  }
  const productDrawer = ref(false)
  const videoDialog = ref(false)

  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)
  const dialogspec = ref(false)
  const disabled = ref(false)

  // 自定义参数
  const selfData = ref([
    {
      name: '',
      val: '',
    },
  ])
  // 添加自定义参数
  const addParameter = () => {
    let temp = {
      name: '',
      val: '',
    }
    selfData.value.push(temp)
  }
  // 删除自定义参数
  const deleteParameter = (index, id) => {
    selfData.value = selfData.value.filter((o, i) => i != index)
    if (id) {
      paraForm.itemIDs.push(id)
    }
  }
  // 穿梭框 -----start------

  const insData = ref([])
  const filtervalue = ref([]) // 选中的说明书

  const videoData = ref([])
  const videoValue = ref([]) // 选中的视

  // 刷新页面
  const refresh = () => {
    useSettingStore().setReload()
  }

  // 说明书弹窗
  const productDrawerShow = () => {
    insData.value = []
    productDrawer.value = true
    const tmp = {
      limit: 0,
      name: '',
      page: 0,
    }
    instrList(tmp).then((res) => {
      res.data.data.rows.forEach((item) => {
        insData.value.push({
          key: item.id,
          label: item.name,
        })
      })
    })
  }

  // 视频弹窗
  const vidoeDrawerShow = () => {
    videoData.value = []
    videoDialog.value = true
    const tmp = {
      limit: 0,
      name: '',
      page: 0,
    }
    videoList(tmp).then((res) => {
      res.data.data.rows.forEach((item) => {
        if (videoData.value.indexOf(item) == -1) {
          videoData.value.push({
            key: item.id,
            label: item.name,
          })
        }
      })
    })
  }

  const filterMethod = (query, item) => {
    return item.label.toLowerCase().includes(query.toLowerCase())
  }

  const filterVideo = (query, item) => {
    return item.label.toLowerCase().includes(query.toLowerCase())
  }

  // 保存说明书
  const saveInsbooks = () => {
    productDrawer.value = false
  }

  // 保存视频
  const saveVideo = () => {
    videoDialog.value = false
  }

  // 穿梭框----end----

  // 商品规格 ----start------

  // 选择的规格内容
  const listData = ref([])
  const connentArr = ref([]) // 保存重复的数量
  const indexArr = ref([]) // 保存重复的间隔index
  const form = ref({})
  const specData = ref([])
  const nameIndex = ref(1)
  const tableData = ref([
    {
      code: '', //sku
      enabled: true, //启用
      image: '', //主图
      name: `默认规格${nameIndex.value}`,
      price: '0', //价格
      overPrice: '0', //过保价格
      warrantyDay: '30', //质保
    },
  ])
  const delSepcIds = ref([]) // 删除的商品规格ID集合
  // 规格类型数据
  const selectspecdata = ref([
    {
      value: 'a',
      title: '品牌',
      checkList: ['美的', '格力', '海尔'],
    },
    {
      value: 'b',
      title: '颜色',
      checkList: ['白色', '黑色', '灰色', '红色'],
    },
    {
      value: 'c',
      title: '尺寸',
      checkList: ['10cm', '20cm', '30cm'],
    },
    {
      value: 'd',
      title: '内存',
      checkList: ['1G', '2G', '5G', '10G'],
    },
  ])
  interface SpanMethodProps {
    rowIndex: number
    columnIndex: number
  }

  const objectSpanMethod = ({ rowIndex, columnIndex }: SpanMethodProps) => {
    const vals = Object.values(form.value)
    if (columnIndex > 0) {
      if (columnIndex <= vals.length) {
        const index = indexArr.value[columnIndex - 1].indexOf(rowIndex)
        if (index !== -1) {
          return {
            rowspan: connentArr.value[columnIndex - 1][index],
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      }
    }
  }

  // 商品规格内容变化
  const changeModel = (val) => {
    form.value = {}
    listData.value.forEach((o) => {
      if (o.checkList.length > 0) {
        form.value[o.value] = o.checkList
      }
    })
    tableData.value = []
    var arrGroup = Object.values(form.value)
    var arrStack = []
    var strStack = []
    combination(arrStack, strStack, arrGroup, arrGroup.length, 0)
    connentArr.value = []
    indexArr.value = []
    const obj = _.cloneDeep(form.value) // 记录数量
    for (const i in obj) {
      obj[i] = []
    }
    const obj2 = _.cloneDeep(obj) // 记录位置

    for (const j in obj) {
      let save = ''
      let num = -1
      for (const i in tableData.value) {
        if (save === tableData.value[i][j]) {
          obj[j][num]++
        } else {
          num++
          obj[j].push(1)
          obj2[j].push(Number(i))
        }
        save = tableData.value[i][j]
      }
    }
    for (const i in form.value) {
      connentArr.value.push(obj[i])
      indexArr.value.push(obj2[i])
    }
  }
  /**
   * arrStack
   * strStack
   * arrGroup 数组
   * size 数组长度
   * index 下标
   * **/
  const combination = (arrStack, strStack, arrGroup, size, index) => {
    var nextIndex = index + 1
    if (nextIndex > size) {
      return
    }
    arrStack.push(arrGroup[index])
    if (arrStack.length === size) {
      combinationResult(strStack, arrStack, 0)
    }
    combination(arrStack, strStack, arrGroup, size, nextIndex)
    if (arrStack.length > 0) {
      arrStack.pop()
    }
    combination(arrStack, strStack, arrGroup, size, nextIndex)
  }
  //  合并选择的数组信息
  const combinationResult = (strStack, arrGroup, index) => {
    if (index + 1 > arrGroup.length) {
      return
    }
    var arr = arrGroup[index]
    var nextIndex = index + 1
    for (var i = 0; i < arr.length; i++) {
      strStack.push(arr[i])
      combinationResult(strStack, arrGroup, nextIndex)
      if (nextIndex + 1 > arrGroup.length) {
        const obj = {}
        let count = 0
        for (const j in form.value) {
          obj[j] = strStack[count]
          count++
        }
        let name = []
        for (const o in obj) {
          name.push(obj[o])
        }

        let tem = {
          name: name.join('、'),
          image: '',
          enabled: true,
          price: '0',
          overPrice: '0',
          warrantyDay: '30',
          code: '',
        }
        tableData.value.push({ ...tem, ...obj })
        if (tableData.value.length == 0) {
          tableData.value = [
            {
              name: '默认规格',
              image: '',
              enabled: true,
              price: '0',
              overPrice: '0',
              warrantyDay: '30',
              code: '',
            },
          ]
        }
      }
      if (strStack.length > 0) {
        strStack.pop()
      }
    }
  }

  // 修改商品规格弹窗  确定
  const Confirm = () => {
    images.value = []
    tableData.value = [
      {
        name: '默认规格',
        image: '',
        enabled: true,
        price: '0',
        overPrice: '0',
        warrantyDay: '30',
        code: '',
      },
    ]
    specData.value = selectspecdata.value.filter((o) => {
      if (checkList.value.includes(o.value)) {
        return o
      }
    })
    listData.value = specData.value.map((o) => {
      return { ...o, checkList: [] }
    })
    dialogspec.value = false
  }

  // 添加商品规格
  const addLineData = () => {
    nameIndex.value += 1
    let tt = tableData.value.some((i) => {
      return i.name == `默认规格${nameIndex.value}`
    })
    if (tt) {
      addLineData()
      return
    }
    tableData.value.push({
      code: '',
      enabled: true,
      image: '',
      name: `默认规格${nameIndex.value}`,
      price: '0',
      overPrice: '0',
      warrantyDay: '30',
    })
  }

  // 删除商品规格
  const deleteLineData = (index, obj) => {
    tableData.value.splice(index, 1)
    if (tableData.value.length == 0) {
      nameIndex.value = 0
    }
    images.value.splice(index, 1)
    if (obj.id) {
      delSepcIds.value.push(obj.id)
    }
    if (obj.image != '') {
      deleteFile([obj.image]).then()
    }
  }

  // 商品规格 ----- end-----

  const checkList = ref([])

  const options = [
    {
      value: true,
      label: '启用',
    },
    {
      value: false,
      label: '关闭',
    },
  ]

  const options2 = [
    {
      value: '成品',
      label: '成品',
    },
    {
      value: '配件',
      label: '配件',
    },
  ]

  const activeNames = ref(['1', '2', '4', '5'])

  const handleChange = (val: string) => {
    if (activeNames.value.includes(val)) {
      activeNames.value = activeNames.value.filter((o) => o != val)
    } else {
      activeNames.value.push(val)
    }
  }
  const itemIndex = ref(0)

  const rightW = ref(0)
  const lookW = ref(null)
  const dom = ref()

  const resizeObserver = new ResizeObserver((val) => {
    lookW.value = val[0].borderBoxSize[0].inlineSize
    rightW.value = window.innerWidth - document.body.clientWidth
  })

  // 销毁dom监听
  onBeforeUnmount(() => {
    resizeObserver.disconnect()
    // document.body.removeEventListener('scroll', listener.value)
  })

  // 获取商品图片
  const getProImages = (uploadFile: UploadFile) => {
    if (infoForm.fileList.indexOf(uploadFile) == -1) {
      infoForm.fileList.push(uploadFile)
    }
  }

  // 删除图片
  const handleRemove = (file: UploadFile) => {
    infoForm.fileList.forEach((item, index) => {
      if (item.url == file.url) {
        infoForm.fileList.splice(index, 1)
        infoForm.imageIDs.push(item.id)
      }
    })
  }

  // 放大查看图片
  const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
  }

  const imageIndex = ref() // 图片下标
  const images = ref([]) // 上传到商品规格图片
  const imgRoutes = ref([]) // 删除的商品规格图片路径

  // 上传商品规格图片
  const handleChangeImg: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    tableData.value[imageIndex.value].image = window.URL.createObjectURL(uploadFile.raw)
    images.value[imageIndex.value] = uploadFile
  }

  // 获取下标
  const getImgIndex = (i) => {
    imageIndex.value = i
  }

  const loading = ref(false)

  const formInfo = ref() // 基本信息表单Dom

  const formSpec = ref() // 商品规格表单Dom

  // （上传）获取图片
  const handleChange1 = (uploadFile: UploadFile, item) => {
    if (item.uploadSize < uploadFile.size / 1024 / 1024) {
      ElMessage({
        showClose: true,
        message:
          item.type == 5
            ? '图片'
            : item.type == 6
            ? '附件'
            : '视频' + '大小不能超过' + item.uploadSize + 'MB!',
        type: 'error',
        duration: 2000,
      })
      return
    }
    if (item.imgarr.length >= item.uploadQty) {
      ElMessage({
        showClose: true,
        message: `${item.type == 5 ? '图片' : item.type == 6 ? '附件' : '视频'} 数量不能超过 ${
          item.uploadQty
        }!`,
        type: 'error',
        duration: 2000,
      })
      return
    }
    let { uid, name } = uploadFile.raw
    let tmp = {
      uid,
      name,
      image: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
    }
    item.imgarr.push(tmp)
  }
  // 删除图片
  const deleteItem1 = (itindex, index) => {
    paraForm.fieldInfo = paraForm.fieldInfo.map((arr) => {
      if (arr.type == 5 || arr.type == 6 || arr.type == 7) {
        if (arr.goodsParamFieldId == itindex.goodsParamFieldId) {
          arr.imgarr = arr.imgarr.filter((o, i) => i != index)
        }
      }
      return arr
    })
  }
  // 查看图片
  const file = ref({ file: null, type: '' }) //文件
  const dialogContract = ref(false) //文件查看弹窗
  const lookFile = (val, type) => {
    file.value = { file: val, type: type }
    dialogContract.value = true
  }
  //监听弹窗关闭时销毁 iframe内存
  watch(dialogContract, (n) => {
    if (!n) {
      file.value.file = 'about:blank'
    }
  })
  // 基本信息表单数据
  const infoForm = reactive({
    proID: '',
    status: false, // 商品状态
    type: nodekey == '1' ? '成品' : '配件', // 商品类型
    model: '', // 商品型号
    class: '', // 商品分类id
    className: '', // 商品分类名称
    brand: '', // 商品品牌id
    brandName: '', // 商品品牌名称
    unit: '', // 商品单位id
    unitName: '', // 商品单位名称
    name: '', // 商品名称
    item: '', // 商品货号
    war: true, // 质保登记
    code: '', // 商品编号
    fileList: [], // 商品图片
    supplier: '', // 供应商
    phone: '', // 供应商电话
    images: [], // 商品图片
    imageIDs: [], // 删除的商品图片ID集合
    factoryIds: [], // 品牌商家id集合
  })

  const typeOptions = ref([]) // 分类下拉
  const brandOptions = ref([]) // 品牌下拉
  const unitOptions = ref([]) // 单位下拉

  const typeLoading = ref(false)
  const brandLoading = ref(false)
  const unitLoading = ref(false)

  const typeVal = ref()
  const brandVal = ref()
  const unitVal = ref()

  const wangEdior = ref()
  const ediorData = ref({ content: '', type: 'goods' })

  // 检验规则
  const rulesForm = reactive<FormRules>({
    type: [{ required: true, message: '请选择商品类型', trigger: 'blur' }],
    model: [{ required: true, message: '请输入商品型号', trigger: 'blur' }],
    class: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
    brand: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
    unit: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
    name: [{ required: false, message: '请输入商品名称', trigger: 'blur' }],
    item: [{ required: false, message: '请输入商品货号', trigger: 'blur' }],
    war: [{ required: true, message: '请选择质保登记', trigger: 'change' }],
    code: [{ required: false, message: '请输入商品编号', trigger: 'blur' }],
    para: [{ required: false, message: '请选择商品参数', trigger: 'blur' }],
    supplier: [{ required: false, message: '请输入供应商名称', trigger: 'blur' }],
    phone: [
      { required: false, message: '请输入供应商联系电话', trigger: 'blur' },
      {
        pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的电话',
        trigger: 'blur',
      },
    ],
  })

  // 商品参数表单数据
  const paraForm = reactive({
    paraOptions: [], // 参数下拉数据
    para: '', // 选择参数Id
    paraId: null, //获取商品参数值ID，新增不必传，修改必传
    fieldInfo: [], // 自定义字段内容list
    fieldValVos: [], //获取商品list ，新增不必传，修改必传
    paramValVo: {
      fieldValVos: null,
      id: null, //商品参数值ID，新增不必传，修改必传
      paramId: null, //商品参数ID
    }, // 商品参数对象
    itemIDs: [], // 删除的商品自定义参数ID
  })

  // 商品类型变化时
  const typeChange = (val) => {
    if (val == '成品') {
      listItem.value = ['基本信息', '商品规格', '商品参数', '商品资料', '商品详情']
      rulesForm.brand[0].required = true
    } else {
      rulesForm.brand[0].required = false
      listItem.value = ['基本信息', '商品规格', '商品参数', '商品详情']
    }
  }

  // 获取分类下拉
  const getTypeOptions = async (name: string) => {
    typeLoading.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await typePageSelect(data)
    typeOptions.value = res.data.data.rows
    typeLoading.value = false
  }

  // 搜索分类下拉数据
  const searchTypeSelect = _.throttle((query: string) => {
    if (typeVal.value !== query) {
      typeVal.value = query
      getTypeOptions(typeVal.value)
    }
  }, 500)

  // 获取品牌下拉数据
  const getBrandOptions = async (name: string) => {
    brandLoading.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await brandPageSelect(data)
    brandOptions.value = res.data.data.rows
    if (brandOptions.value.length > 0 && !infoForm.brand) {
      infoForm.brand = res.data.data.rows[0].id
    }
    brandLoading.value = false
  }

  // 搜索品牌下拉数据
  const searchBrandSelect = _.throttle((query: string) => {
    if (brandVal.value !== query) {
      brandVal.value = query
      getBrandOptions(brandVal.value)
    }
  }, 500)

  // 获取单位下拉数据
  const getUnitOptions = async (name: string) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await unitPageSelect(data)
    unitOptions.value = res.data.data.rows
  }

  // 搜索类型下拉数据
  const searchUnitSelect = (query: string) => {
    if (unitVal.value !== query) {
      unitVal.value = query
      getUnitOptions(unitVal.value)
    }
  }

  // 获取参数下拉数据
  const getparaOptions = async (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await paramPageSelect(data)
    paraForm.paraOptions = res.data.data.rows
  }

  // 商品参数改变时
  const getFields = (val) => {
    paraForm.fieldInfo = []
    if (val != '') {
      getParamFields(val).then((res) => {
        if (res.data.data.rows.length > 0) {
          paraForm.fieldInfo = res.data.data.rows.map((o) => {
            o.goodsParamFieldId = o.id
            o.id = null
            if (o.type == 5 || o.type == 6 || o.type == 7) {
              o.val = []
              o.imgarr = []
            } else if (o.type == 4) {
              o.val = []
            } else {
              o.val = ''
            }
            if (paraForm.paramValVo.paramId == val) {
              paraForm.fieldValVos.map((item) => {
                if (o.goodsParamFieldId == item.goodsParamFieldId) {
                  o.goodsParamFieldId = item.goodsParamFieldId
                  o.id = item.id
                  if (item.type == 5 || item.type == 6 || item.type == 7) {
                    o.imgarr = [...JSON.parse(item.val)]
                  } else if (item.type == 4) {
                    o.val = [...JSON.parse(item.val)]
                  }
                }
              })
            }
            return o
          })
        }
      })
    } else {
      paraForm.fieldInfo = []
    }
  }

  // 请求的数据
  const getData = async () => {
    // 获取分类名称
    if (infoForm.class) {
      typeOptions.value.forEach((item) => {
        if (item.id == infoForm.class) {
          infoForm.className = item.name
        }
      })
    }
    // 获取品牌名称
    if (infoForm.brand) {
      brandOptions.value.forEach((item) => {
        if (item.id == infoForm.brand) {
          infoForm.brandName = item.name
        }
      })
    }
    // 获取单位名称
    if (infoForm.unit) {
      unitOptions.value.forEach((item) => {
        if (item.id == infoForm.unit) {
          infoForm.unitName = item.name
        }
      })
    }
    // 上传商品图片
    if (infoForm.fileList.length != 0) {
      const files = []
      infoForm.fileList.forEach((item) => {
        if (item.raw) {
          files.push(item.raw)
        }
      })
      if (files.length != 0) {
        infoForm.images = []
        await proAnnexUpload(files).then((res) => {
          res.data.data.rows.forEach((item) => {
            infoForm.images.push({
              image: item,
            })
          })
        })
      }
    }
    // 上传商品规格图片
    if (images.value.length != 0) {
      const files = []
      let indexArr = []
      images.value.forEach((item, i) => {
        if (item.raw) {
          files.push(item.raw)
          indexArr.push(i)
        }
        if (imgRoutes.value[i] != item) {
          deleteFile([imgRoutes.value[i]]).then()
        }
      })
      if (files.length != 0) {
        await proAnnexUpload(files).then((res) => {
          res.data.data.rows.forEach((item, i) => {
            tableData.value[indexArr[i]].image = item
          })
        })
      }
    }

    if (infoForm.imageIDs.length != 0) {
      deleteFile(infoForm.imageIDs).then()
    }
    // 获取商品过保价格
    tableData.value.forEach((item) => {
      if (!item.overPrice) {
        item.overPrice = '0'
      }
    })
    // 判断规格是否重复
    let isRepeat
    if (tableData.value.length > 1) {
      const newArr = tableData.value.map((item) => item.name)
      isRepeat = newArr.some((x, index, arr) => arr.findIndex((y) => y == x) != index)
    }
    if (isRepeat) {
      ElMessage({
        message: '规格名称重复',
        type: 'warning',
        duration: 2000,
      })
      return
    }
    paraForm.paramValVo.fieldValVos = paraForm.fieldInfo

    // 判断商品图片、附件、视频 上传
    if (paraForm.para) {
      for (const key in paraForm.paramValVo.fieldValVos) {
        let item = paraForm.paramValVo.fieldValVos[key]
        if (item.type == 4) {
          item.val = JSON.stringify(item.val)
        }
        if (item.type == 5 || item.type == 6 || item.type == 7) {
          let img = [] //新上传的
          let isImg = [] //已经上传的
          for (const i in item.imgarr) {
            const it = item.imgarr[i]
            if (it.file) {
              img.push(it.file)
            } else {
              isImg.push(it)
            }
          }
          if (img.length > 0) {
            if (item.type == 7) {
              await orderVideoUpload(img).then((res) => {
                if (res.data.success) {
                  for (let i = 0; i < res.data.data.rows.length; i++) {
                    item.val.push({ id: null, image: res.data.data.rows[i] })
                  }
                } else {
                  if (res.data.isError)
                    ElMessage({
                      message: res.data.message,
                      type: 'error',
                    })
                }
              })
            } else {
              await orderAnnexUpload(img).then((res) => {
                if (res.data.success) {
                  for (let i = 0; i < res.data.data.rows.length; i++) {
                    item.val.push({ id: null, image: res.data.data.rows[i] })
                  }
                } else {
                  if (res.data.isError)
                    ElMessage({
                      message: res.data.message,
                      type: 'error',
                    })
                }
              })
            }
          }
          item.val = [...isImg, ...item.val]
          if (item.type == 5 || item.type == 6 || item.type == 7) {
            item.val = JSON.stringify(item.val)
          }
        }
      }
    }
    // 获取商品参数
    if (paraForm.paramValVo.paramId == paraForm.para) {
      paraForm.paramValVo.id = paraForm.paraId
    }
    paraForm.paramValVo.paramId = paraForm.para

    wangEdior.value.getDeleteImages()
    return {
      brand: infoForm.brandName,
      brandId: infoForm.brand,
      code: infoForm.code,
      content: wangEdior.value.getValue(),
      customParamVos:
        selfData.value.length == 1 && selfData.value[0].name == '' && selfData.value[0].val == ''
          ? []
          : selfData.value,
      delCustomParamIds: paraForm.itemIDs,
      delImageIds: infoForm.imageIDs,
      delSepcIds: delSepcIds.value,
      delextendPathIds: [],
      enabledRegister: infoForm.war,
      extendPathVos: [],
      id: infoForm.proID == '' ? null : infoForm.proID,
      imageVos: infoForm.images,
      instructionBookIds: filtervalue.value,
      itemNumber: infoForm.item,
      model: infoForm.model,
      name: infoForm.name,
      paramValVo: paraForm.paramValVo,
      specVos: tableData.value,
      status: infoForm.status,
      supplier: infoForm.supplier,
      supplierTelephone: infoForm.phone,
      type: infoForm.className,
      typeId: infoForm.class,
      unit: infoForm.unitName,
      unitId: infoForm.unit,
      videoIds: videoValue.value,
      factoryIds: infoForm.factoryIds,
    }
  }

  // 保存方法
  const saveSuccess = (method, data, load) => {
    if (!data) {
      return
    }
    if (data.paramValVo.fieldValVos) {
      data.paramValVo.fieldValVos = data.paramValVo.fieldValVos.map((item) => {
        let tem = []
        if (item.type === 5 || item.type === 6 || item.type === 7) {
          let v = JSON.parse(item.val)
          tem = v.map((o) => {
            return { id: null, optValue: o.image }
          })
        } else if (item.type === 4) {
          let v = JSON.parse(item.val)
          tem = v.map((o) => {
            return { id: null, optValue: o }
          })
        } else {
          tem = [{ id: null, optValue: item.val }]
        }
        return { ...item, optVos: tem }
      })
    }
    load.value = true
    method(data).then((res) => {
      load.value = false
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 2000,
        })
      if (res.data.success == true) {
        refresh()
        TagsViewStore.delView(router.currentRoute.value.path)
        if (data.id) {
          router.push({ path: '/commodity/commodi/detail/' + data.id })
        } else {
          router.push({ path: '/commodity/commodi' })
        }
      }
    })
  }
  // 取消保存
  const onCancel = () => {
    TagsViewStore.delView(router.currentRoute.value.path)
    if (infoForm.proID) {
      router.push({ path: '/commodity/commodi/detail/' + infoForm.proID })
    } else {
      router.push({ path: '/commodity/commodi' })
    }
  }
  // 保存商品/配件
  const saveData = async (formEl: FormInstance | undefined) => {
    // 判断自定义字段必填项
    let result = await formSpec.value.validate(async (val) => {
      return val
    })
    formEl.validate(async (valid) => {
      if (valid && result) {
        if (infoForm.type == '成品') {
          saveSuccess(productSave, await getData(), loading)
        } else {
          saveSuccess(spareSave, await getData(), loading)
        }
      } else {
        ElMessage({
          message: '请输入完整信息！',
          type: 'error',
        })
        return
      }
    })
  }

  // 获取商品详细
  const getDetail = async () => {
    if (route.params.id != undefined) {
      loading.value = true
      // 成品 商品详情 1
      if (nodekey == '1') {
        await getInfo(route.params.id).then((res) => {
          infoForm.proID = res.data.data.row.id
          infoForm.model = res.data.data.row.model
          infoForm.class = res.data.data.row.typeId
          infoForm.className = res.data.data.row.type
          infoForm.brand = res.data.data.row.brandId
          infoForm.brandName = res.data.data.row.brand
          infoForm.unit = res.data.data.row.unitId
          infoForm.unitName = res.data.data.row.unit
          infoForm.name = res.data.data.row.name
          infoForm.item = res.data.data.row.itemNumber
          infoForm.war = res.data.data.row.enabledRegister
          infoForm.code = res.data.data.row.code
          infoForm.status = res.data.data.row.status
          rulesForm.name[0].required = true
          rulesForm.item[0].required = true
          rulesForm.code[0].required = true
          infoForm.images = res.data.data.row.imageVos
          infoForm.factoryIds = res.data.data.row.factoryIds

          if (res.data.data.row.imageVos.length != 0) {
            res.data.data.row.imageVos.forEach((item) => {
              infoForm.fileList.push({
                id: item.id,
                url: item.image,
              })
            })
          }
          tableData.value = res.data.data.row.specVos
          res.data.data.row.specVos.forEach((item) => {
            images.value.push(item.image)
            imgRoutes.value.push(item.image)
          })
          nameIndex.value = 0
          paraForm.paraId = res.data.data.row.paramValVo?.id //修改必填
          paraForm.para = res.data.data.row.paramValVo?.paramId
          paraForm.paramValVo.paramId = res.data.data.row.paramValVo?.paramId
          paraForm.fieldValVos = res.data.data.row.paramValVo?.fieldValVos || []
          if (res.data.data.row.paramValVo) {
            getParamFields(paraForm.para).then((res2) => {
              paraForm.fieldInfo = res2.data.data.rows.map((item) => {
                item['goodsParamFieldId'] = item.id
                item.id = null
                return item
              })
              paraForm.fieldInfo = paraForm.fieldInfo.map((o) => {
                if (o.type == 5 || o.type == 6 || o.type == 7) {
                  o.val = []
                  o.imgarr = []
                } else if (o.type == 4) {
                  o.val = []
                } else {
                  o.val = ''
                }
                paraForm.fieldValVos.map((item) => {
                  if (o.goodsParamFieldId == item.goodsParamFieldId) {
                    // o.goodsParamFieldId = item.goodsParamFieldId
                    o.id = item.id
                    if (item.type == 5 || item.type == 6 || item.type == 7) {
                      let ov = item.optVos.map((vo) => {
                        return { id: vo.id, image: vo.optValue }
                      })
                      o.imgarr = [...ov]
                    } else if (item.type == 4) {
                      let ov = item.optVos.map((vo) => vo.optValue)
                      o.val = [...ov]
                    } else {
                      o.val = item.optVos.map((vo) => vo.optValue)[0]
                    }
                  }
                })
                return o
              })
            })
          }
          if (res.data.data.row.customParamVos.length == 0) {
            selfData.value = [
              {
                name: '',
                val: '',
              },
            ]
          } else {
            selfData.value = res.data.data.row.customParamVos
          }
          ediorData.value = { content: res.data.data.row.content, type: 'goods' }
        })
        await getInsDetail(route.params.id).then((res) => {
          filtervalue.value = res.data.data.row
        })
        await getVideoDetail(route.params.id).then((res) => {
          videoValue.value = res.data.data.row
        })
      } else {
        await getSpareInfo(route.params.id).then((res) => {
          infoForm.proID = res.data.data.row.id
          infoForm.model = res.data.data.row.model
          infoForm.class = res.data.data.row.typeId
          infoForm.className = res.data.data.row.type
          infoForm.brand = res.data.data.row.brandId
          infoForm.brandName = res.data.data.row.brand
          infoForm.unit = res.data.data.row.unitId
          infoForm.unitName = res.data.data.row.unit
          infoForm.name = res.data.data.row.name
          infoForm.item = res.data.data.row.itemNumber
          infoForm.code = res.data.data.row.code
          infoForm.status = res.data.data.row.status
          ediorData.value = { content: res.data.data.row.content, type: 'goods' }
          rulesForm.name[0].required = true
          rulesForm.item[0].required = true
          rulesForm.code[0].required = true
          infoForm.images = res.data.data.row.imageVos
          infoForm.factoryIds = res.data.data.row.factoryIds
          if (res.data.data.row.imageVos.length != 0) {
            res.data.data.row.imageVos.map((item) => {
              infoForm.fileList.push({
                id: item.id,
                url: item.image,
              })
            })
          }
          tableData.value = res.data.data.row.specVos
          nameIndex.value = 0
          paraForm.paraId = res.data.data.row.paramValVo?.id //修改必填
          paraForm.para = res.data.data.row.paramValVo?.paramId
          paraForm.paramValVo.paramId = res.data.data.row.paramValVo?.paramId
          paraForm.fieldValVos = res.data.data.row.paramValVo?.fieldValVos
          if (res.data.data.row.paramValVo) {
            getParamFields(paraForm.para).then((res2) => {
              paraForm.fieldInfo = res2.data.data.rows.map((item) => {
                item['goodsParamFieldId'] = item.id
                item.id = null
                return item
              })
              paraForm.fieldInfo = paraForm.fieldInfo.map((o) => {
                if (o.type == 5 || o.type == 6 || o.type == 7) {
                  o.val = []
                  o.imgarr = []
                } else if (o.type == 4) {
                  o.val = []
                } else {
                  o.val = ''
                }
                paraForm.fieldValVos.map((item, i) => {
                  if (o.goodsParamFieldId == item.goodsParamFieldId) {
                    // o.goodsParamFieldId = item.goodsParamFieldId
                    o.id = item.id
                    if (item.type == 5 || item.type == 6 || item.type == 7) {
                      let ov = item.optVos.map((vo) => {
                        return { id: vo.id, image: vo.optValue }
                      })
                      o.imgarr = [...ov]
                    } else if (item.type == 4) {
                      let ov = item.optVos.map((vo) => vo.optValue)
                      o.val = [...ov]
                    } else {
                      o.val = item.optVos.map((vo) => vo.optValue)[0]
                    }
                  }
                })
                return o
              })
            })
          }
          if (res.data.data.row.customParamVos.length == 0) {
            selfData.value = [
              {
                name: '',
                val: '',
              },
            ]
          } else {
            selfData.value = res.data.data.row.customParamVos
          }
        })
      }
      loading.value = false
    }
  }

  const onShowSystemUpgrade = () => {
    ElMessage({
      type: 'success',
      message: '正在升级维护中，敬请期待',
    })
  }

  onMounted(() => {
    // 监听dom的变化
    resizeObserver.observe(dom.value)
    // // 监听滚动条滚动的位置
    // document.body.addEventListener(
    //   'scroll',
    //   (listener.value = function () {
    //     var scrollPosition =
    //       window.scrollY || document.documentElement.scrollTop || document.body.scrollTop
    //     if (scrollPosition >= document.getElementById('sy4').offsetTop - 60) {
    //       itemIndex.value = 4
    //     } else if (scrollPosition >= document.getElementById('sy3')?.offsetTop - 60) {
    //       itemIndex.value = 3
    //     } else if (scrollPosition >= document.getElementById('sy2').offsetTop - 60) {
    //       itemIndex.value = 2
    //     } else if (scrollPosition >= document.getElementById('sy1').offsetTop - 60) {
    //       itemIndex.value = 1
    //     } else if (scrollPosition >= document.getElementById('sy0').offsetTop) {
    //       itemIndex.value = 0
    //     }
    //   }),
    // )

    new Promise(() => {
      getUnitOptions('')
      getparaOptions('')
      getFactoryOptional('')
      getFactorySelectPageFn(getFactoryOptionalParam.value)
      getDetail()
      getBrandOptions('')
      getTypeOptions('')
    })
    if (localStorage.getItem('nodeKey') == '2') {
      listItem.value = ['基本信息', '商品规格', '商品参数', '商品详情']
    }
    if (paraForm.paraId || selfData.value[0].name) {
      activeNames.value.push('3')
    }
  })
</script>
<style lang="scss" scoped>
  @import './index.scss';
</style>
